var express = require('express');
var router = express.Router();
const path = require('path');
// 导入moment
const moment = require('moment');

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync');
const AccountModel = require('../models/AccountModel');
const adapter = new FileSync(path.resolve(__dirname, '../data/db.json'));
// 获取db对象
const db = low(adapter);

// 记账本列表
router.get('/account', function (req, res, next) {
  // 获取所有的账单信息
  AccountModel.find().sort({ time: -1 }).exec().then((result) => {
    res.render('list', { accounts: result, moment });
  }).catch(() => {
    res.status(500).send('查询失败')
  })

});

// 添加记录
router.get('/account/create', function (req, res, next) {
  res.render('create')
});

// 新增记录
router.post('/account', function (req, res, next) {
  // 获取请求体数据
  //插入数据库
  AccountModel.create({ ...req.body, time: moment(req.body.time).toDate() })
    .then(() => {
      res.render('success', { msg: '添加成功', url: '/account' })
    }).catch(err => {
      res.status(500).send(err)
    })
});

// 删除记录
router.get('/account/:id', (req, res) => {
  // 获取params的id参数
  let { id } = req.params;
  AccountModel.deleteOne({ _id: id }).then(() => {
    res.render('success', { msg: '删除成功', url: '/account' })
  }).catch((err) => {
    console.log(err);
    res.status(500).send('删除失败')
  })
})

module.exports = router;
